package com.dts.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.IOException;
import java.util.Collection;

@WebServlet(name ="fileServlet" ,urlPatterns = "/fileServlet")
@MultipartConfig
public class  FileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try{
            request.setCharacterEncoding("utf-8");
            Collection<Part> parts = request.getParts();
            for (Part part : parts) {
                String filename = part.getSubmittedFileName();
                String path = request.getServletContext().getRealPath("/file/") + filename;
                part.write(path);
            }
            request.setAttribute("message", "文件上传成功!");
        }catch (Exception e){
            request.setAttribute("message", "上传失败，原因："+e.getMessage());
        }
        // 跳转到 message.jsp
        getServletContext().getRequestDispatcher("/success.jsp").forward(request, response);
    }
}
